<?php

class controller_product extends controller_theme
{

	public function __construct()
	{
		parent::__construct();
	}


	public function listing()
	{
		$category_id = get('category_id', 0, 'int');

		$model = bone::get_model('product', APP_DIR);
		$template = bone::get_template('product.listing', APP_DIR);

		$pagination = $template->get_pagination();
		$pagination->set_total($model->get_sum($category_id));
		$pagination->set_page(get('page', 1, 'int'));
		$pagination->set_url('./?controller=product&task=listing');

		$products = $model->get_list( $category_id );
		$categories = $model->get_categories();
		
		$template->set_title('产品列表');
		$template->set('category_id', $category_id);
		$template->set('products', $products);
		$template->set('categories', $categories);
		$template->set_data($this->get_data());
		$template->display();
	}


	public function edit()
	{
		$product_id = get('product_id', 0, 'int');

		$product = bone::get_table('product');
		$product->load($product_id);

		$model = bone::get_model('product', APP_DIR);
		$categories = $model->get_categories();

		$template = bone::get_template('product.edit', APP_DIR);
		if($product_id)
			$template->set_title('编辑产品');
		else
			$template->set_title('添加产品');

		$template->set('product', $product);
		$template->set('categories', $categories);
		$template->set_data($this->get_data());
		$template->display();
	}


	public function edit_save()
	{
		$id = post('id', 0, 'int');
		$my = bone::get_user();

		$product = bone::get_table('product');
		if($id) $product->load($id);
		$product->bind($_POST);
		$product->create_time = time();
		$product->save();

		$image = $_FILES['image'];
		if($image['error']==0)
		{
			$img = bone::get('image');
			$img->open( $image['tmp_name'] );

			if( $img->is_image() )
			{
				$img->resize_to(200, 200);
				$img->save_to( BONE_ROOT.DS.'storage'.DS.'product'.DS.'large_'.$product->id.'.'.$img->get_type());

				$img->resize_to(100, 100);
				$img->save_to( BONE_ROOT.DS.'storage'.DS.'product'.DS.$product->id.'.'.$img->get_type());
				$product->image = $product->id.'.'.$img->get_type();
			}
		}
		$product->save();

		if( $id ){$msg = '修改产品成功';}else{$msg = '添加产品成功';}
		$this->redirect('./?controller=product&task=listing&category_id='.$product->category_id, $msg);
	}


	public function delete()
	{
		$product_id = get('product_id', 0, 'int');
		if(!$product_id) exit;

		$product = bone::get_table('product');
		$product->delete( $product_id );
		
		$this->redirect('./?controller=product&task=listing', '删除产品成功');
	}



	
}
?>